#include "match.h"
#include "player.h"
#include "turn.h"
#include "frame_controller.h"

Match::Match()
{
    _currentPlayerIter = _players.end();
    //FrameController::getInstance().onTurn([](const PinScheme& s){});
    FrameController::getInstance().updateFrameReq();
    _connection = FrameController::getInstance().onTurn(boost::bind(&Match::onTurn, this, _1));
}

Match::~Match()
{
    _connection.disconnect();
}
    
void Match::attachPlayer(std::shared_ptr<Player> player)
{

    assert( std::find(_players.begin(), _players.end(), player) == _players.end() );
    _players.push_back(player);

}

void Match::makeTurn(const PinScheme& scheme)
{

    assert(!_players.empty());

    if (_currentPlayerIter == _players.end())
    {
        _currentPlayerIter = _players.begin();
    }
    
    Player* player = _currentPlayerIter->get();
    player->makeTurn(scheme);
    
    if (player->isFrameDone())
    {
        ++_currentPlayerIter;
    }
}

bool Match::isDone() const
{
    return _isDone;
}

void Match::onTurn(PinScheme scheme)
{
    makeTurn(scheme);
}

void Match::printPlayersScores() const
{
    for (auto& p : _players)
    {
        p->printScores();
    }
}